package com.vk.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vk.project.annotation.AuthCheck;
import com.vk.project.common.BaseResponse;
import com.vk.project.common.DeleteRequest;
import com.vk.project.common.ErrorCode;
import com.vk.project.common.ResultUtils;
import com.vk.project.constant.CommonConstant;
import com.vk.project.constant.UserConstant;
import com.vk.project.exception.BusinessException;
import com.vk.project.model.dto.userinterfaceinfo.UserInterfaceInfoAddRequest;
import com.vk.project.model.dto.userinterfaceinfo.UserInterfaceInfoQueryRequest;
import com.vk.project.model.dto.userinterfaceinfo.UserInterfaceInfoUpdateRequest;
import com.vk.project.model.enums.InterfaceInfoStatusEnum;
import com.vk.project.model.vo.ChartVO;
import com.vk.project.model.vo.UserInterfaceInfoVO;
import com.vk.project.service.InterfaceInfoService;
import com.vk.project.service.UserInterfaceInfoService;
import com.vk.project.service.UserService;
import com.vk.vkapicommon.model.entity.InterfaceInfo;
import com.vk.vkapicommon.model.entity.User;
import com.vk.vkapicommon.model.entity.UserInterfaceInfo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName : InterfaceInfoController
 * @Description : 用户和接口关系管理控制器
 * @Author : LYQ
 * @Date: 2023-12-08 15:23
 */
@Slf4j
@RestController
@RequestMapping("/userInterfaceInfo")
public class UserInterfaceInfoController {

    @Autowired
    private UserInterfaceInfoService userInterfaceInfoService;

    @Autowired
    private InterfaceInfoService interfaceInfoService;

    @Autowired
    private UserService userService;

    /**
     * 创建用户和接口关系
     *
     * @param interfaceInfoAddRequest 创建用户和接口关系请求对象
     * @param request                 请求体
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<String> addUserInterfaceInfo(@RequestBody UserInterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        // 判断请求参数是否为空
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断用户是否已经申请过接口
        UserInterfaceInfoQueryRequest userInterfaceInfoQueryRequest = new UserInterfaceInfoQueryRequest();
        userInterfaceInfoQueryRequest.setUserId(interfaceInfoAddRequest.getUserId());
        userInterfaceInfoQueryRequest.setInterfaceInfoId(interfaceInfoAddRequest.getInterfaceInfoId());
        BaseResponse<List<UserInterfaceInfoVO>> listUserInterfaceInfo = this.listUserInterfaceInfo(userInterfaceInfoQueryRequest);
        // 如果查询到的结果大于 0
        if(listUserInterfaceInfo.getData().size() > 0){
            int num = userInterfaceInfoService.getleftNumByUserIdAndInterfaceId(interfaceInfoAddRequest.getUserId(), interfaceInfoAddRequest.getInterfaceInfoId());
            // 如果用户剩余次数为零
            if(num == 0) {
                // 重新增加调用次数
                userInterfaceInfoService.addBy50Times(interfaceInfoAddRequest.getUserId(), interfaceInfoAddRequest.getInterfaceInfoId());
                // 返回结果
                return BaseResponse.success("开通成功！");
            } else {    // 如果用户剩余次数不为零
                // 返回结果
                return BaseResponse.failure(30000,"用户尚有调用次数，请勿重复开通！");
            }
        }
        // 创建UserInterfaceInfo对象
        UserInterfaceInfo interfaceInfo = new UserInterfaceInfo();
        // 进行参数复制
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验参数
        userInterfaceInfoService.validUserInterfaceInfo(interfaceInfo, true);
        // 获取登录用户
        User loginUser = userService.getLoginUser(request);
        // 设置用户ID
        interfaceInfo.setUserId(loginUser.getId());
        // 设置状态
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        // 保存参数
        boolean result = userInterfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        // 获取新添加的UserInterfaceInfo的ID
        long newUserInterfaceInfoId = interfaceInfo.getId();
        // 返回结果
        return BaseResponse.success("开通成功！");
    }

    /**
     * 删除用户和接口关系
     *
     * @param deleteRequest 删除请求对象
     * @param request       请求体
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserInterfaceInfo oldUserInterfaceInfo = userInterfaceInfoService.getById(id);
        if (oldUserInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldUserInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = userInterfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新用户和接口关系
     *
     * @param interfaceInfoUpdateRequest 更新用户和接口关系请求对象
     * @param request                    请求体
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUserInterfaceInfo(@RequestBody UserInterfaceInfoUpdateRequest interfaceInfoUpdateRequest, HttpServletRequest request) {
        // 如果请求体为空或者id为空，抛出参数错误异常
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将请求体中的数据复制到新的UserInterfaceInfo对象中
        UserInterfaceInfo interfaceInfo = new UserInterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        userInterfaceInfoService.validUserInterfaceInfo(interfaceInfo, false);
        // 获取当前登录用户
        User user = userService.getLoginUser(request);
        // 获取要修改的UserInterfaceInfo对象的id
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        UserInterfaceInfo oldUserInterfaceInfo = userInterfaceInfoService.getById(id);
        // 不存在，抛出未找到错误异常
        if (oldUserInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldUserInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = userInterfaceInfoService.updateById(interfaceInfo);
        // 修改数据，返回修改结果
        return ResultUtils.success(result);
    }

    /**
     * 根据Id获取用户和接口关系信息
     *
     * @param id 用户Id
     * @return 返回用户和接口关系信息
     */
    @GetMapping("/get")
    public BaseResponse<UserInterfaceInfo> getUserInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 根据id获取用户信息
        UserInterfaceInfo interfaceInfo = userInterfaceInfoService.getById(id);
        // 返回用户信息
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取用户和接口关系列表
     *
     * @param interfaceInfoQueryRequest 查询请求对象
     * @return 返回用户和接口关系列表
     */
    @PostMapping("/list")
    public BaseResponse<List<UserInterfaceInfoVO>> listUserInterfaceInfo(@RequestBody UserInterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        // 创建用户和接口关系查询对象
        UserInterfaceInfo interfaceInfoQuery = new UserInterfaceInfo();
        // 如果查询请求不为空，则将查询请求的属性复制到用户和接口关系查询对象中
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        // 创建查询条件构造器
        LambdaQueryWrapper<UserInterfaceInfo> queryWrapper = new LambdaQueryWrapper<>(interfaceInfoQuery);
        queryWrapper.eq(UserInterfaceInfo::getStatus,1);
        // 根据查询条件查询用户和接口关系
        List<UserInterfaceInfoVO> interfaceInfoVOS = userInterfaceInfoService.list(queryWrapper).stream()
                .map(userInterfaceInfo -> {
                    InterfaceInfo interfaceInfo = interfaceInfoService.getById(userInterfaceInfo.getInterfaceInfoId());
                    UserInterfaceInfoVO userInterfaceInfoVO = new UserInterfaceInfoVO();
                    BeanUtils.copyProperties(userInterfaceInfo, userInterfaceInfoVO);
                    userInterfaceInfoVO.setInterfaceInfo(interfaceInfo);
                    return userInterfaceInfoVO;
                })
                .collect(Collectors.toList());
        // 返回用户和接口关系列表
        return ResultUtils.success(interfaceInfoVOS);
    }

    /**
     * 分页获取用户和接口关系列表
     *
     * @param interfaceInfoQueryRequest 查询用户和接口关系请求
     * @param request                   请求体
     * @return 返回用户和接口关系列表
     */
    @GetMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserInterfaceInfo>> listUserInterfaceInfoByPage(UserInterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        // 如果传入的参数为空，抛出参数错误的异常
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将传入的参数赋值给接口信息查询对象
        UserInterfaceInfo interfaceInfoQuery = new UserInterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        // 获取当前页码
        long current = interfaceInfoQueryRequest.getCurrent();
        // 获取每页显示的记录数
        long size = interfaceInfoQueryRequest.getPageSize();
        // 获取排序字段
        String sortField = interfaceInfoQueryRequest.getSortField();
        // 获取排序顺序
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建查询条件
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        // 添加排序条件
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        // 创建分页对象
        Page<UserInterfaceInfo> interfaceInfoPage = userInterfaceInfoService.page(new Page<>(current, size), queryWrapper);
        // 返回查询结果
        return ResultUtils.success(interfaceInfoPage);
    }

    /**
     * 获取已发放次数
     *
     * @return 返回已发放次数
     */
    @GetMapping("/getIssuedTimes")
    public BaseResponse<Integer> getIssuedTimes() {
        return ResultUtils.success(userInterfaceInfoService.getIssuedTimes());
    }

    /**
     * 获取累计调用
     *
     * @return 返回累计调用
     */
    @GetMapping("/getAccumulatedCalls")
    public BaseResponse<Integer> getAccumulatedCalls() {
        return ResultUtils.success(userInterfaceInfoService.getAccumulatedCalls());
    }

    /**
     * 获取用户调用次数
     *
     * @return 返回数据
     */
    @GetMapping("/getNumberOfUserCalls")
    public BaseResponse<List<ChartVO>> getNumberOfUserCalls() {
        return ResultUtils.success(userInterfaceInfoService.getNumberOfUserCalls());
    }

    /**
     * 获取各个接口的调用次数
     *
     * @return 返回数据
     */
    @GetMapping("/getNumberOfInterfaceCalls")
    public BaseResponse<List<ChartVO>> getNumberOfInterfaceCalls() {
        return ResultUtils.success(userInterfaceInfoService.getNumberOfInterfaceCalls());
    }
}
